#include "daemon_runner.h"

typedef struct
{
    char *path;
    char *args;
    pid_t pid;
} sub_process_t;

void daemon_runner_check_process(sub_process_t *process)
{
    if (process->pid > 0)
    {
        // 证明进程启动过, 现在是否还活着需要检测
        pid_t pid = waitpid(process->pid, NULL, WNOHANG);
        if (pid == 0)
        {
            log_info("子进程正在运行: %s(%d)", process->path, process->pid);
            return;
        }
        else if (pid > 0)
        {
            log_info("子进程已结束: %s(%d)", process->path, process->pid);
        }
        else
        {
            perror("waitpid出错");
        }
    }

    // 启动该进程:  要么第一次启动  要么进程挂掉了
    process->pid = -1;
    pid_t pid = fork();

    if (pid == 0)
    {
        log_info("启动子进程: %s", process->path);
        execl(process->path, process->path, process->args, NULL);

        // 启动失败
        perror("启动子进程失败");
        log_error("%s", process->path);
    }
    else if (pid > 0)
    {
        process->pid = pid;
    }
    else
    {
        perror("fork出错");
    }
}
void daemon_runner_run(void)
{
    /*
        1. 后台进程
        2. 关闭键盘输入  (标准输出 错误输出 重定向到文件)
    */
    // 参数1:要不切换到根目录(0 =cd /) 参数2: 0 重定向到黑洞 1不
    daemon(0, 1);
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    open("/dev/null", O_RDWR);                         // 输入重定向
    open("/root/gateway.log", O_RDWR | O_CREAT, 0666); // 输出重定向
    open("/root/gateway.log", O_RDWR | O_CREAT, 0666); // 错误重定向

    sub_process_t app_process = {
        .path = "/usr/bin/gateway",
        .args = "app",
        .pid = -1};

    sub_process_t ota_process = {
        .path = "/usr/bin/gateway",
        .args = "ota",
        .pid = -1};

    while (1)
    {
        daemon_runner_check_process(&app_process);
        daemon_runner_check_process(&ota_process);
        sleep(1);
    }
}
